package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * @param article 需要更新文章的静态页面地址
     * @param content 生成静态页面内容需要
     */
    @Override
    @Async
    public void buildStaticHtmlToMinio(ApArticle article, String content) {

        try {
            //1、获取模板对象
            Template template = configuration.getTemplate("article.ftl");

            //2、准备填充数据
            List<Map> list= JSON.parseArray(content,Map.class);

            Map map = new HashMap();
            map.put("content",list);

            //3、生成静态页面并存储到minio中
            StringWriter sw = new StringWriter();
            template.process(map, sw);
            byte[] bytes = sw.toString().getBytes();

            //4、上传html页面到minio中
            String path = fileStorageService.uploadHtmlFile("", article.getId() + ".html", new ByteArrayInputStream(bytes));

            //5、将path更新到article中
            article.setStaticUrl(path);
            apArticleMapper.updateById(article);

            //将ap_article和ap_article_content中content的值内容要同步到es
            syncAparticleToEs(article,content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }


    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 同步文章到search_service中
     * @param article
     * @param content
     */
    private void syncAparticleToEs(ApArticle article, String content) {

        SearchArticleVo searchArticleVo= new SearchArticleVo();
        BeanUtils.copyProperties(article,searchArticleVo);
        searchArticleVo.setContent(content);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(searchArticleVo));

    }
}
